package com.changzhi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changzhi.common.constans.Constants;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.DateUtil;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.vo.GiftConfigVo;
import com.changzhi.ldyl.model.vo.GoddessVo;
import com.changzhi.ldyl.model.vo.UserVo;
import com.changzhi.mapper.ActivityRecordMapper;
import com.changzhi.mapper.ActivityWalletMapper;
import com.changzhi.service.ActivityService;
import com.changzhi.service.GiftService;
import com.changzhi.service.GoddessService;
import com.changzhi.service.UserService;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: 小落
 * @date: 2021年02月25日
 */
@Slf4j
@Service
public class GoddessServiceImpl implements GoddessService {

	@Autowired
	private ActivityService activityService;
	@Autowired
	private RedisUtil redisUtil;
	@Resource
	private ActivityRecordMapper activityRecordMapper;
	@Resource
	private ActivityWalletMapper activityWalletMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private GiftService giftService;
	public final static Map<String, LocalDateTime> TIME_MAP = new HashMap<>();
	public final static Integer ACTIVITY_ID = 10;

	/*@PostConstruct
	public void init(){
		redisUtil.del(RedisConstans.ACTIVITY + ACTIVITY_ID);
		Activity activity2 = activityService.getActivity(ACTIVITY_ID);
		//存活动时间
		TIME_MAP.put("startTime", activity2.getStartTime());
		TIME_MAP.put("endTime", activity2.getEndTime());
	}*/

	@Override
	public void doMqDataByUserGift(UserGift userGift) {
		if(userGift.getTotalGiftValue() == 0){
			return;
		}
		//2.是否在活动时间内
		if(!DateUtil.isBetweenTime(TIME_MAP.get("startTime"), TIME_MAP.get("endTime"))){
			return;
		}
		//3.指定礼物
		Map<Integer, Integer> map = activityService.someGiftIdList(ACTIVITY_ID, 2);
		if(map.get(userGift.getGiftId()) == null){
			return;
		}
		//
		Integer value = userGift.getTotalGiftValue() * 10;
		String userId = userGift.getUserId();
		String targetId = userGift.getTargetId();
		//3.增加骑士点
		ActivityWallet wallet1 = activityService.getActivityWallet(ACTIVITY_ID, userId);
		String key1 = RedisConstans.putRediskey(RedisConstans.ACTIVITY_FLAG, ACTIVITY_ID, userId);
		if (redisUtil.get(key1) != null) {
			wallet1 = new ActivityWallet();
			wallet1.setActivityId(ACTIVITY_ID);
			wallet1.setUserId(userId);
			wallet1.setAmount1(value);
			activityWalletMapper.insert(wallet1);
			redisUtil.set(key1, 1, RedisConstans.ONE_MONTH);
		} else{
			activityWalletMapper.addAmount1(wallet1.getId(), value);
		}
		//4.增加女神点
		ActivityWallet wallet2 = activityService.getActivityWallet(ACTIVITY_ID, targetId);
		String key2 = RedisConstans.putRediskey(RedisConstans.ACTIVITY_FLAG, ACTIVITY_ID, targetId);
		if (redisUtil.get(key2) == null) {
			wallet2 = new ActivityWallet();
			wallet2.setActivityId(ACTIVITY_ID);
			wallet2.setUserId(targetId);
			wallet2.setAmount2(value);
			activityWalletMapper.insert(wallet2);
			redisUtil.set(key2, 1, RedisConstans.ONE_MONTH);
		} else{
			activityWalletMapper.addAmount2(wallet2.getId(), value);
		}
		//5.删除排行榜缓存
		redisUtil.del(RedisConstans.GODDESS_RANKING);
		rankings();
	}

	@Override
	public List<UserVo> rankings() {
		List<UserVo> list = redisUtil.get(RedisConstans.GODDESS_RANKING);
		if(!CollectionUtils.isEmpty(list)){
			return list;
		}
		list = activityWalletMapper.selectRankings(ACTIVITY_ID);
		int row = 1;
		for (UserVo userVo : list) {
			if(row == 1){
				userVo.setLabel("荣耀女神");
			} else if(row == 2){
				userVo.setLabel("紫星女神");
			} else if(row == 3){
				userVo.setLabel("蔷薇女神");
			}
			userVo.setRank(row);
			row++;
		}
		redisUtil.set(RedisConstans.GODDESS_RANKING, list, RedisConstans.ONE_HOUR);
		return list;
	}

	@Override
	public GoddessVo userInfo(String userId) {
		GoddessVo result = new GoddessVo();
		User user = userService.getUser(userId);
		if(user == null){
			throw new ServiceException("用户不存在");
		}
		//
		ActivityWallet wallet = activityService.getActivityWallet(ACTIVITY_ID, userId);
		Integer status0 = 0;//状态；0=未达到领取条件;1=可领取;2=已领取
		Integer status1 = 0;
		if(hasReceive(userId, 0)){
			status0 = 2;
		} else {
			if(wallet != null && (wallet.getAmount1() >= 100000 || wallet.getAmount2() >= 100000)){
				status0 = 1;
			}
		}
		if(hasReceive(userId, 1)){
			status1 = 2;
		} else {
			if(wallet != null && (wallet.getAmount1() >= 1000000 || wallet.getAmount2() >= 1000000)){
				status1 = 1;
			}
		}
		//返回
		result.setUserId(user.getUserId())
				.setAccountId(user.getAccountId())
				.setNickname(user.getNickname())
				.setAvatarUrl(StringUtils.isBlank(user.getAvatarUrl()) ? Constants.DEFAULT_AVATAR: user.getAvatarUrl())
				.setRideValue(wallet == null ? 0 : wallet.getAmount1())
				.setGoddessValue(wallet == null ? 0 : wallet.getAmount2())
				.setStatus0(status0)
				.setStatus1(status1);
		return result;
	}

	private boolean hasReceive(String userId,Integer type){
		LambdaQueryWrapper<ActivityRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityRecord::getActivityId, ACTIVITY_ID).eq(ActivityRecord::getUserId, userId).eq(ActivityRecord::getType, type).last("limit 1");
		ActivityRecord record = activityRecordMapper.selectOne(wrapper);
		if(record == null){
			return false;
		}
		return true;
	}

	@Override
	public GiftConfigVo receiveAward(String userId, Integer type) {
		if(!DateUtil.isBetweenTime(TIME_MAP.get("startTime"), TIME_MAP.get("endTime"))){
			throw new ServiceException("不在活动时间内");
		}
		if(type == null){
			throw new ServiceException("类型不能为空");
		}
		//是否已领取
		if(hasReceive(userId, type)){
			throw new ServiceException("已领取奖励");
		}
		//骑士点/女神点数
		ActivityWallet wallet = activityService.getActivityWallet(ACTIVITY_ID, userId);
		if(type == 0){
			if(wallet == null || (wallet.getAmount1() < 100000 && wallet.getAmount2() < 100000)){
				throw new ServiceException("骑士点/女神点数不足");
			}
		} else {
			if(wallet == null || (wallet.getAmount1() < 1000000 && wallet.getAmount2() < 1000000)){
				throw new ServiceException("骑士点/女神点数不足");
			}
		}
		ActivityPrize prize = activityService.getPrize(ACTIVITY_ID, type);
		if(prize == null){
			throw new ServiceException("奖品不存在");
		}
		//保存奖品
		GiftConfig giftConfig = giftService.savePrize(ACTIVITY_ID, userId, prize.getGiftId(), type, prize.getNum());
		GiftConfigVo vo = new GiftConfigVo();
		vo.setName(giftConfig.getName()).setIcon(giftConfig.getIconUrl());
		return vo;
	}
}
